package com.example.hellonotes.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.text.format.DateFormat;

/**
 * 
 * @author Administrator
 *  处理日期的工具类
 */

public class DateUtils {
	
//	"created_at": "Wed Jun 17 14:26:24 +0800 2015"

	public static final long ONE_MINUTE_MILLIONS = 60 * 1000;
	public static final long ONE_HOUR_MILLIONS = 60 * ONE_MINUTE_MILLIONS;
	public static final long ONE_DAY_MILLIONS = 24 * ONE_HOUR_MILLIONS;

	public static String getShortTime(String dateStr) {
		String str = "";
		
		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
		try {
			Date date = sdf.parse(dateStr);
			Date curDate = new Date();
			long durTime = curDate.getTime() - date.getTime();
			
			/**
			 * 调用方法  如果返回值是0 表示微博是当天发送的 如果是是负数表示是几天前发布的
			 */
			int dayStatus = calculateDayStatus(date, curDate);
			/**
			 * 如果当前时间减去微博的发送时间小于十分钟         刚刚
			 * 如果大于十分钟小于一小时					xx分钟前
			 * 如果大于一小时  但是是当天发布的				XX小时前
			 * 如果是昨天发布的（-1）						昨天+小时+分钟
			 * 如果同年									月+日
			 * 不同年									年+月+日
			 */
			if(durTime <= 10 * ONE_MINUTE_MILLIONS) {
				str = "刚刚";
			} else if(durTime < ONE_HOUR_MILLIONS) {
				str = durTime / ONE_MINUTE_MILLIONS + "分钟前";
			} else if(dayStatus == 0) {
				str = durTime / ONE_HOUR_MILLIONS + "小时前";
			} else if(dayStatus == -1) {
				str = "昨天" + DateFormat.format("HH:mm", date);
			} else if(isSameYear(date, curDate) && dayStatus < -1) {
				str = DateFormat.format("MM-dd", date).toString();
			} else {
				str = DateFormat.format("yyyy-MM", date).toString();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return str;
	}
	
	
	/**
	 * 下面的方法判断是不是同年
	 */
	public static boolean isSameYear(Date targetTime, Date compareTime) {
		Calendar tarCalendar = Calendar.getInstance();
		tarCalendar.setTime(targetTime);
		int tarYear = tarCalendar.get(Calendar.YEAR);
		
		Calendar compareCalendar = Calendar.getInstance();
		compareCalendar.setTime(compareTime);
		int comYear = compareCalendar.get(Calendar.YEAR);
		
		return tarYear == comYear;
	}
	
	/**
	 * 下面的方法使用  Calendar日历类  来获取单独的天 值
	 * 返回当前天数和微博发送时间的天数的差值
	 * 
	 */
	
	public static int calculateDayStatus(Date targetTime, Date compareTime) {
		Calendar tarCalendar = Calendar.getInstance();
		tarCalendar.setTime(targetTime);
		int tarDayOfYear = tarCalendar.get(Calendar.DAY_OF_YEAR);
		
		Calendar compareCalendar = Calendar.getInstance();
		compareCalendar.setTime(compareTime);
		int comDayOfYear = compareCalendar.get(Calendar.DAY_OF_YEAR);
		
		return tarDayOfYear - comDayOfYear;
	}
}
